<script setup>
import { ref, defineEmits, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updateApi } from '@/api/warehousingentry/warehousingEntryDetailsSort'
import { addApi } from '@/api/warehousingentry/warehousingEntryUp'
import { getSkuInfoApi } from '@/api/item'
import eventBus from '@/utils/eventBus'

const emit = defineEmits(['refresh'])
const ruleFormRef = ref(null)
const rules = ref({
  warehouseId: [
    { required: true, message: '请选择仓库', trigger: 'blur' }
  ],
  warehouseAreaId: [
    { required: true, message: '请选择库区', trigger: 'blur' }
  ],
  warehouseAreaLocaId: [
    { required: true, message: '请选择库位', trigger: 'blur' }
  ]
})

const dialogVisible = ref(false)
const dialogFormData = ref({
  id: null,
  skuId: null,
  skuName: '',
  serialNumber: '',
  count: '',
  warehouseId: null,
  warehouseAreaId: null,
  warehouseAreaLocaId: null, // 注意这里拼写可能有误，应该是 warehouseAreaLocalId
  detailsSortId: null,
  warehouseList: [],        // 添加这些字段
  warehouseAreaList: [],    // 添加这些字段
  warehouseAreaLocalList: [] // 添加这些字段
})
const resetForm = () => {
  dialogVisible.value = false
  dialogFormData.value = {
    id: null,
    skuId: null,
    skuName: '',
    serialNumber: '',
    count: '',
    warehouseId: null,
    warehouseAreaId: null,
    warehouseAreaLocaId: null,
    detailsSortId: null,
    warehouseList: [],
    warehouseAreaList: [],
    warehouseAreaLocalList: []
  }
  ruleFormRef.value?.resetFields()
}
const itemInfo = ref()
const getItemList = async () => {
  let res = await getSkuInfoApi()
  itemInfo.value = res
}
// 监听 skuId 变化，自动设置商品名称
watch(() => dialogFormData.value.skuId, (newSkuId) => {
  if (newSkuId && itemInfo.value.length > 0) {
    const sku = itemInfo.value.find(item => item.id === newSkuId)
    if (sku) {
      dialogFormData.value.skuName = sku.title || ''
      dialogFormData.value.serialNumber = sku.code || ''
    }
  }
})
const confirm = async () => {
  if (!ruleFormRef.value) return

  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        // 先更新分拣表状态为已上架
        const updateRes = await updateApi({
          id: dialogFormData.value.id,
          status: 3, // 已上架状态
          count: dialogFormData.value.count
        })

        if (updateRes.code) {
          // 创建上架记录
          const upData = {
            skuId: dialogFormData.value.skuId,
            warehouseId: dialogFormData.value.warehouseId,
            warehouseAreaId: dialogFormData.value.warehouseAreaId,
            warehouseAreaLocaId: dialogFormData.value.warehouseAreaLocaId,
            count: dialogFormData.value.count,
            detailsSortId: dialogFormData.value.id,
            status: 2 // 已上架状态
          }
          const upRes = await addApi(upData)
          if (upRes.code) {
            ElMessage.success('上架成功!')
            resetForm()
            emit('refresh')
            eventBus.emit('refreshUpPage')
          } else {
            ElMessage.error('上架失败！')
          }
        } else {
          ElMessage.error('更新分拣状态失败！')
        }
      } catch (error) {
        ElMessage.error('操作异常！')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

defineExpose({
  dialogFormData,
  dialogVisible,
  itemInfo
})
onMounted(() => {
  getItemList()
})

</script>

<template>
  <el-dialog v-model="dialogVisible" title="上架信息" width="600px">
    <el-form :model="dialogFormData" label-width="120px" ref="ruleFormRef" :rules="rules">
      <el-form-item label="商品名称">
        <el-input v-model="dialogFormData.skuName" disabled />
      </el-form-item>
      <el-form-item label="序列号">
        <el-input v-model="dialogFormData.serialNumber" disabled />
      </el-form-item>
      <el-form-item label="上架数量">
        <el-input v-model="dialogFormData.count" disabled />
      </el-form-item>

      <el-form-item label="仓库" prop="warehouseId">
        <el-select v-model="dialogFormData.warehouseId" placeholder="请选择仓库">
          <el-option v-for="warehouse in dialogFormData.warehouseList" :key="warehouse.id" :label="warehouse.name"
            :value="warehouse.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="库区" prop="warehouseAreaId">
        <el-select v-model="dialogFormData.warehouseAreaId" placeholder="请选择库区">
          <el-option v-for="area in dialogFormData.warehouseAreaList" :key="area.id" :label="area.name"
            :value="area.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="库位" prop="warehouseAreaLocaId">
        <el-select v-model="dialogFormData.warehouseAreaLocaId" placeholder="请选择库位">
          <el-option v-for="local in dialogFormData.warehouseAreaLocalList" :key="local.id" :label="local.locaCode"
            :value="local.id" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>